/**
 * @author 
 * @time 2022-04-19 19PM
 * @description 项目配置文件目录
 */

import axios from 'axios'
import store from '../store'

/**
 * 创建axios实例对象，来进行通用数据封装
 */
const Axios = axios.create({
    baseURL: '/xinyuanapp'
})

/**
 * 拦截分为请求前拦截和请求后拦截
 */
Axios.interceptors.request.use(config => {
    let token = store.getters['common/token']

    /**
     * 1. 判断是否需要权限拦截
     * 2. 判断是否有权限
     */
    let _urls = ['/get/code', '/login/byphone','/register','/suggest/info']
    if (_urls.includes(config.url)) return config

    /** 返回错误信息 */
    if (!token) return Promise.reject({ code: 400, message: '用户没有登录' })

    /** 添加token到请求头中 */
    config.headers.token = token
    return config
})



Axios.interceptors.response.use(response => {
    /**
     * 判断是否是通用错误，如：400
     */
    let { data } = response
    if (data.code === 400) {
        // alert(data.message)
        return Promise.reject(data)
    }

    return response
})

/**
 * 封装的axios请求方法
 * @param {{url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', data: any, params: any}} _request 
 * @returns 
 */
export default function(_request) {
    // Axios.request(config: AxiosRequestConfig): Promise
    return new Promise(resolve => {
        Axios.request({
            url: _request.url,
            method: _request.method || 'post',
            data: _request.data || {},
            params: _request.params || {},
            // onUploadProgress?: (progressEvent: any) => void
            onUploadProgress: _request.cb || (() => {})
        }).then(({ data }) => {
            // console.log(data)
            resolve(data)
        }).catch(e => {
            console.log(e)
            resolve({ code: 800, message: '请求出错' })
        })
    })
}